package com.example.springbootmybatis.service.impl;

import com.example.springbootmybatis.common.PageResult;
import com.example.springbootmybatis.entity.UserTab;
import com.example.springbootmybatis.mapper.UserMapper;
import com.example.springbootmybatis.param.UserParam;
import com.example.springbootmybatis.service.IUserService;
import com.example.springbootmybatis.vo.UserDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service("user1") //标记为服务处理，让spring将其加载到beanfactory中，以提供依赖注入
@Transactional //事务支持
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询指定用户信息
     * @param id 用户id
     * @return 对应用户
     */
    public UserTab getUserByid(Integer id) {
        return userMapper.getUserByid(id);
    }

    @Override
    public List<UserTab> selectAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public UserTab addUser(UserTab user) {
        if(user.getDeptId() == null){
            user.setDeptId(0);
        }
        userMapper.addUser(user);
        return user;
    }

    @Override
    public UserTab updateUser(UserTab user) {
        userMapper.updateUser(user);
        return user;
    }

    @Override
    public void del(Integer id) {
        userMapper.del(id);
    }

    @Override
    public PageResult getUserByPage(Integer pageNum, Integer pageSize, String userName) {
        PageResult<UserTab> page = new PageResult<UserTab>(pageNum, pageSize);
        Long count = userMapper.getUserCount(userName);
        page.setTotalCount(count);
        if(count == null || count.intValue() == 0){
            page.setPageData(null);
        }else{
            List<UserTab> userTabs = userMapper.getUserByPage(page.getStartRow(), pageSize, userName);
            page.setPageData(userTabs);
        }
        return page;
    }

    @Override
    public PageResult getUserDetailByPage(UserParam userParam) {
        PageResult<UserDetail> page = new PageResult<UserDetail>(userParam.getPageNum(), userParam.getPageSize());
        Long count = userMapper.getUserDetailCount(userParam);
        page.setTotalCount(count);
        if(count == null || count.intValue() == 0){
            page.setPageData(null);
        }else{
            List<UserDetail> userDetails = userMapper.getUserDetailByPage(userParam);
            page.setPageData(userDetails);
        }
        return page;
    }

    @Override
    public UserTab login(UserTab user) {
        return userMapper.login(user);
    }
}
